package service

import (
	"github.com/gin-gonic/gin"
	"monitoring-api/models"
	"monitoring-api/pkg/jwt"
	"monitoring-api/serializer"
)

// UserLoginService 管理用户注册服务
type UserLoginService struct {
	Email    string `form:"email" json:"email"`
	Password string `form:"password" json:"password" binding:"required,min=6,max=40"`
}

// Login 用户登录函数
func (service *UserLoginService) Login(c *gin.Context) serializer.Response {
	var user models.User

	if err := models.MySql.Where("email = ?", service.Email).First(&user).Error; err != nil {
		return serializer.ParamErr("账号或密码错误", nil)
	}

	if user.CheckPassword(service.Password) == false {
		return serializer.ParamErr("账号或密码错误", nil)
	}
	// 生成token
	token, err := jwt.GenToken(int64(user.UserID), user.Name)
	if err != nil {
		return serializer.ParamErr("登录失败", err)
	}
	return serializer.BuildUserResponse(user, token)
}
